﻿using System;
using System.Diagnostics.Contracts;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal struct ExtProp
    {
        public static ExtProp Create (ExtPropType type, SpreadsheetColor color)
        {
            ExtProp p = new ExtProp();
            Contract.Assert(Enum.IsDefined(typeof (ExtPropType), type));
            p.extType = type;
            p.value = FullColorExt.Create(color);
            return p;
        }
        public ExtPropType extType;
        //private ushort __cb;
        public ExtPropValueBase value;

        public ExtProp(ExtPropType type, ExtPropValueBase value)
        {
            this.extType = type;
            this.value = value;
        }

        public void Read(BinaryReader reader)
        {
#if DEBUG
            ReadWriteChecker.CheckStruct((ref ExtProp t, BinaryReader r) => t.Read(r),
                                         (ref ExtProp t, BinaryWriter w) => t.Write(w), reader, ref this);
#endif
            extType = (ExtPropType)reader.ReadUInt16();
            Contract.Assert(Enum.IsDefined(typeof (ExtPropType), extType));
            ushort __cb = reader.ReadUInt16();
            switch (extType)
            {
                case ExtPropType.BackgroundColor:
                    case ExtPropType.ForegroundColor:
                    case ExtPropType.BottomBorderColor:
                    case ExtPropType.CellTextColor:
                    case ExtPropType.DiagonalBorderColor:
                    case ExtPropType.LeftBorderColor:
                    case ExtPropType.RightBorderColor:
                    case ExtPropType.TopBorderColor:
                        value = new FullColorExt();
                    break;
                    case ExtPropType.FontScheme:
                    case ExtPropType.Indentation:
                    value = new IntExt();
                    break;
                case ExtPropType.GradientFill:
                    value = new XFExtGradient();
                    break;
                default:
                    throw new NotSupportedException();
            }
            value.Read(reader);
            Contract.Assert(__cb == value.Length + 4);
        }

        public void Write(BinaryWriter writer)
        {
            writer.Write((ushort)extType);
            writer.Write(((ushort)(value.Length + 2 + 2)));
            value.Write(writer);

        }

    }
}